import { useState, useEffect } from 'react'
import { useModelStore } from '@/store/modelStore'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Button } from '@/components/ui/button'
import toast from 'react-hot-toast'

interface ModelSelectorProps {
  providerId: string
  onModelAdded?: () => void
}

export function ModelSelector({ providerId, onModelAdded }: ModelSelectorProps) {
  const { models, loading, selectedModel, loadModels, setSelectedModel, addNewModel } =
    useModelStore()
  const [search, setSearch] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [customModel, setCustomModel] = useState('')
  const [isCustom, setIsCustom] = useState(false)

  const filteredModels = models.filter(model => {
    const keywords = search.trim().toLowerCase().split(/\s+/)
    const target = model.id.toLowerCase()
    return keywords.every(kw => target.includes(kw))
  })

  useEffect(() => {
    if (providerId) {
      loadModels(providerId)
    }
  }, [providerId])

  // 当选择模型时的处理
  const handleModelChange = (value: string) => {
    if (value === 'custom') {
      setIsCustom(true)
      setSelectedModel('')
    } else {
      setIsCustom(false)
      setSelectedModel(value)
    }
  }

  const handleSubmit = async () => {
    const modelToSave = isCustom ? customModel : selectedModel
    if (!modelToSave) {
      toast.error('请输入或选择一个模型')
      return
    }
    try {
      setSubmitting(true)
      await addNewModel(providerId, modelToSave)
      toast.success('保存模型成功 🎉')
      // 重置自定义输入
      if (isCustom) {
        setCustomModel('')
        setIsCustom(false)
      }
      // 新增：通知父组件刷新
      if (typeof onModelAdded === 'function') {
        await onModelAdded()
      }
    } catch (error) {
      toast.error('保存失败')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center gap-2 font-bold">
        <span>选择模型</span>
        <Button
          variant="ghost"
          type="button"
          onClick={() => loadModels(providerId)}
          disabled={loading}
        >
          {loading ? '加载中...' : '刷新模型'}
        </Button>
      </div>

      <div className="space-y-4">
        <Select value={isCustom ? 'custom' : selectedModel} onValueChange={handleModelChange}>
          <SelectTrigger className="w-[300px]">
            <SelectValue placeholder="请选择模型" />
          </SelectTrigger>
          <SelectContent>
            <div className="p-2">
              <Input
                placeholder="搜索模型..."
                value={search}
                onChange={e => setSearch(e.target.value)}
                className="h-8"
              />
            </div>
            {filteredModels.map((model, index) => (
              <SelectItem key={`${model.id}-${index}`} value={model.id}>
                {model.name || model.id}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        {isCustom && (
          <Input
            placeholder="请输入自定义模型名称"
            value={customModel}
            onChange={e => setCustomModel(e.target.value)}
            className="w-[300px]"
          />
        )}
      </div>

      <Button 
        onClick={handleSubmit} 
        disabled={submitting || (!selectedModel && !customModel)}
      >
        {submitting ? '保存中...' : '保存模型'}
      </Button>
    </div>
  )
}
